package org.tlipoca.smarticlelike.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.genntii.smcommon.constant.ExceptionConstant;
import org.genntii.smcommon.exception.ArticleAlreadyLikeException;
import org.genntii.smcommon.exception.ArticleNotFoundException;
import org.genntii.smdomain.entity.ArticleLike;
import org.genntii.smdomain.vo.LikeVO;
import org.springframework.stereotype.Service;
import org.tlipoca.smarticlelike.client.ArticleClient;
import org.tlipoca.smarticlelike.mapper.ArticleLikeMapper;
import org.tlipoca.smarticlelike.service.ArticleLikeService;

@Slf4j
@Service
public class ArticleLikeServiceImpl extends ServiceImpl<ArticleLikeMapper, ArticleLike> implements ArticleLikeService {

    @Resource
    private ArticleLikeMapper articleLikeMapper;

    @Resource
    private ArticleClient articleClient;

    @Override
    public LikeVO getArticleLike(Long articleId, Long userId) {
        if (!articleClient.articleExists(articleId).getData()){
            throw new ArticleNotFoundException(ExceptionConstant.ARTICLE_NOT_FOUND_EXCEPTION);
        }
        ArticleLike userArticleLike = articleLikeMapper.getArticleLike(userId,articleId);
        Byte liked = null;
        if (userArticleLike == null){
            liked = 2;
        } else if (userArticleLike.getLike() == 0) {
            liked = 0;
        } else if (userArticleLike.getLike() == 1){
            liked = 1;
        }
        return new LikeVO(articleLikeMapper.getLike(articleId), articleLikeMapper.getDislike(articleId), liked);
    }

    @Override
    public void articleLike(Long articleId, Byte like, Long userId) {
        ArticleLike articleLike = articleLikeMapper.getArticleLike(userId, articleId);
        if (articleLike != null && articleLike.getLike() == like){
            throw new ArticleAlreadyLikeException(ExceptionConstant.LIKE_EXISTS_EXCEPTION);
        } else if (articleLike != null) {
            if (articleLike.getLike() == 1){
                articleLike.setLike((byte) 0);
            } else if (articleLike.getLike() == 0){
                articleLike.setLike((byte) 1);
            }
            articleLikeMapper.updateById(articleLike);
        }else {
            articleLikeMapper.insert(ArticleLike.builder()
                    .articleId(articleId)
                    .like(like)
                    .userId(userId)
                    .build());
        }

        articleClient.setLike(articleLikeMapper.getLike(articleId),articleLikeMapper.getDislike(articleId),articleId);
    }

    @Override
    public void delArticleLike(Long articleId, Long userId) {
        if (!articleClient.articleExists(articleId).getData()){
            throw new ArticleNotFoundException(ExceptionConstant.ARTICLE_NOT_FOUND_EXCEPTION);
        }
        articleLikeMapper.delArticleLike(articleId, userId);
    }

}
